import { useState } from 'react';
import { DndContext, DragOverlay, MouseSensor, TouchSensor, useSensor, useSensors } from '@dnd-kit/core';
import { createPortal } from 'react-dom';
import { Draggable } from './Draggable';
import Item from './Item';
import {
  restrictToWindowEdges, restrictToVerticalAxis, restrictToParentElement, restrictToFirstScrollableAncestor, createSnapModifier
} from '@dnd-kit/modifiers';
const gridSize = 20; // pixels
const snapToGridModifier = createSnapModifier(gridSize);
function App() {
  const [isDragging, setIsDragging] = useState(false);
  const [itemArray, setItemArray] = useState(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20']);
  const [activeId, setActiveId] = useState(null);
  const mouseSensor = useSensor(MouseSensor, {
    // 要求鼠标在激活前移动 10 像素
    activationConstraint: {
      distance: 10,
    },
  });
  const touchSensor = useSensor(TouchSensor, {
    // 按下延迟 250 毫秒，移动容差为 5 像素
    activationConstraint: {
      delay: 250,
      tolerance: 5,
    },
  });
  const sensors = useSensors(mouseSensor, touchSensor);
  return (
    // ASD 修改器存储库包含许多有用的修改器，这些修改器可应用于 DndContext 和 DragOverlay
    // ASD 实际效果是两者叠加，例如：如果DndContext设置的modifiers是[restrictToVerticalAxis]，DragOverlay设置的modifiers是[restrictToWindowEdges]，那么实际效果是两者叠加，即限制在垂直轴上，并且限制在窗口边缘
    <DndContext modifiers={[restrictToFirstScrollableAncestor, snapToGridModifier]} onDragStart={handleDragStart} onDragEnd={handleDragEnd} sensors={sensors}>
      <ul style={{ backgroundColor: '#FBE8E8', overflow: 'scroll', width: '300px', height: '400px' }}>
        {
          itemArray.map(item => (
            <Draggable key={item} id={item}>
              <Item id={item}>
                <div>{item}</div>
              </Item>
            </Draggable>
          ))
        }
      </ul>
      {/* style 直接设置拖动的元素的样式，dropAnimation 设置拖动元素的动画效果，modifiers 设置拖动元素的限制，wrapperElement 设置拖动元素的容器，当拖动的是li的时候设置 */}
      {
        createPortal(<DragOverlay style={{
          width: 100,
          height: 100,
          backgroundColor: 'red',
        }} dropAnimation={{
          duration: 200,
          easing: 'cubic-bezier(0.18, 0.67, 0.6, 1.22)',
        }} wrapperElement="ul">
          {isDragging ? (
            <Item id={activeId} key={activeId}>
              <div>item</div>
            </Item>
          ) : null}
        </DragOverlay>, document.body
        )
      }
    </DndContext>
  );

  function handleDragStart(event) {
    setActiveId(event.active.id);
    setIsDragging(true);
  }

  function handleDragEnd(event) {
    setIsDragging(false);
    setActiveId(null);
  }
}
export default App